<script setup>
import { ref, onMounted, computed } from 'vue'
import resize from '@/views/admin/layout/mixin/resize'
import * as funUser from "@/apis/system/user"
import { createOrUpdate } from "@/utils/config"

const deviceIsPc = computed(() => {
    return resize.getIsPc()
})
const emits = defineEmits(["refreshData"])
const showDialog = ref(false)
const dialogType = ref("")
const dialogData = ref({})
const formRefUserEdit = ref(null)
const formRules = {
    userName: [{ required: true, message: '请输入帐号名', trigger: 'blur' }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' },{ min: 6, max: 32, message: '长度在6到32个字符', trigger: 'blur' }],
    surePassword: [{ required: true, validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请再次输入密码"))
        } else if (value !== this.dialogData.password) {
          callback(new Error("两次输入密码不一致"))
        } else {
          callback()
        }
    }, trigger: 'blur' }],
    isActive: [{ required: true, message: '请选择是否激活', trigger: 'blur' }],
    roleNames: [{ required: true, message: '选择角色', trigger: 'blur' }]
}
const defaultProps = {
    label: 'label',
    children: 'children'
}
const allRoles = ref([])
const treeData = ref([])
const checkedKeys = ref([])

// 初始化数据
onMounted (() => {
    $Common.getBroadcast("bdChangeRole", res => {
        getAllRoles()
    })
    getAllRoles()
})

const open = (row) => {
    if (row && row.id) {
        // 编辑
        dialogType.value = createOrUpdate[1]
        $Common.fullLoading()
        funUser.getDetail({id: row.id}).then(res => {
            $Common.closeFullLoading()
            dialogData.value = { ...res }
            _getUserRole(res)
            showDialog.value = true
        })
    } else {
        // 新增
        dialogType.value = createOrUpdate[0]
        dialogData.value = {
            id: 0,
            userName: "",
            name: "",
            password: "",
            surePassword: "",
            isActive: true,
            roleNames: null,
            surname: "",
            email: "",
            phoneNumber: "",
            lockoutEnabled: false,
        }
        treeData.value = tranceRole(allRoles.value)
        showDialog.value = true
    }
}

const _getUserRole = (data) => {
    funUser.getUserRoles(data).then(res => {
        let names = res.items.map(x => x.name)
        let item = names && names.length > 0 ? { roleNames: names } : null
        treeData.value = tranceRole(allRoles.value, item)
        dialogData.value.roleNames = checkedKeys.value
    })
}

const getAllRoles = async () => {
    funUser.getAssignableRoles().then(res => {
        if (res.items && res.items.length > 0) {
            allRoles.value = res.items
        }
    })
}

const tranceRole = (items, curItem) => {
    let roleData = []
    checkedKeys.value = []
    for (let i in items) {
        let temp = {}
        let item = items[i]
        temp.id = item.name
        temp.label = item.name
        // 有子集递归执行
        if (item.children && item.children.length > 0) {
            temp.children = tranceRole(item.children, curItem)
        }
        if (!curItem) {
            checkedKeys.value = []
        } else {
            // 仅仅将最后一级加入默认选中数组，父级会自动选中，自动展开
            if ((!item.children || item.children.length <= 0) && curItem.roleNames && curItem.roleNames.indexOf(item.name) !== -1) {
                checkedKeys.value.push(item.name)
            }
        }
        roleData.push(temp)
    }
    return roleData
}

const roleTree = ref(null)
const checkChange = (data, isChecked, childChecked) => {
    var curHalfKey = roleTree.value.getHalfCheckedKeys()
    var curKey = roleTree.value.getCheckedKeys()
    var commitKeys = curHalfKey.concat(curKey)
    dialogData.value.roleNames = commitKeys || []
}

const _save = () => {
    formRefUserEdit.value.validate((valid) => {
        if (!valid) return false
        $Common.fullLoading()
        let commitTemp = {
            id: dialogData.value.id,
            userName: dialogData.value.userName,
            name: dialogData.value.name,
            isActive: dialogData.value.isActive,
            roleNames: dialogData.value.roleNames,
            surname: dialogData.value.name,
            email: dialogData.value.userName + "@fljoy.net",
            phoneNumber: "",
            lockoutEnabled: false,
        }
        if (dialogType.value === createOrUpdate[0]) {
            // 新增
            commitTemp.password = dialogData.value.password
            funUser.create(commitTemp).then(res => {
                commonSuccess(null, res)
            })
        } else {
            // 编辑
            funUser.update(commitTemp).then(res => {
                commonSuccess(null, res)
            })
        }
    })
}

const _close = () => {
    showDialog.value = false
    formRefUserEdit.value.resetFields()
}

const commonSuccess = (val, data) => {
    let tips = val || "操作成功!"
    $Common.alert(tips).then(() => {
        $Common.closeFullLoading()
        _close()
        emits("refreshData", data)
    })
}

// 暴露给父组件
defineExpose({
    open
})
</script>

<template>
    <el-dialog title="用户编辑" class="c-el-dialog comp-user-edit-dialog" v-model="showDialog"
        :draggable="true" :before-close="_close" :close-on-click-modal="false" :append-to-body="true">
        <el-form :model="dialogData" ref="formRefUserEdit" :rules="formRules" label-width="100px" size="large">
            <el-form-item label="用户名" prop="userName">
                <el-input placeholder="请输入用户名" v-model="dialogData.userName"></el-input>
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input placeholder="请输入姓名" v-model="dialogData.name"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password" v-if="dialogType === createOrUpdate[0]">
                <el-input type="password" placeholder="请输入6-32位密码" v-model="dialogData.password"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="surePassword" v-if="dialogType === createOrUpdate[0]">
                <el-input type="password" placeholder="请再次输入密码" v-model="dialogData.surePassword"></el-input>
            </el-form-item>
            <el-form-item label="是否激活" prop="isActive">
                <el-radio-group class="c-pw100" v-model="dialogData.isActive">
                    <el-radio :value="false" border style="margin-right: 5px;">否</el-radio>
                    <el-radio :value="true" border>是</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="选择角色" prop="roleNames">
                <div :class="deviceIsPc ? '' : 'role-tree'">
                    <el-tree :props="defaultProps" node-key="id" :data="treeData" :check-strictly="false" :check-on-click-node="true" :default-expanded-keys="checkedKeys"
                        :default-checked-keys="checkedKeys" ref="roleTree" show-checkbox @check="checkChange"></el-tree>
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="_close()">关闭</el-button>
            <el-button type="primary" plain @click="_save()">确定</el-button>
        </template>
    </el-dialog>
</template>

<style lang="scss">
.comp-user-edit-dialog {
    max-width: 520px !important;
    .role-tree {
        margin-top: 6px;
    }
}
</style>